import pyaudio
import pvporcupine
import os
import logging
import pdb


logging.basicConfig(
    #filename = os.path.join(expanduser('~'), 'peoplebank.log'),
    level = logging.DEBUG,
    format = "[%(asctime)s] - %(levelname)s - %(lineno)s] %(message)s",
    datefmt = "%Y-%m-%d %H:%M:%S"
)



# 设备编号
DEVICE_INDEX = 0
# 访问密钥
ACCESS_KEY = os.environ.get('ACCESS_KEY')
print('access key:', ACCESS_KEY)
# 模型位置
MODEL_PATH = 'models/hey-faker_en_mac_v3_0_0.ppn'

def start_agent():
    # 初始化
    porcupine = pvporcupine.create(
      access_key = f'{ACCESS_KEY}',
      keyword_paths = [MODEL_PATH]
    )
    frame_length = porcupine.frame_length
    print(f'frame lenth: {frame_length}')
    # 初始化 PyAudio
    audio = pyaudio.PyAudio()
    # 打开音频流
    stream = audio.open(format=pyaudio.paInt16,
                        channels=1,
                        rate=porcupine.sample_rate,
                        input=True,
                        frames_per_buffer=frame_length)
    logging.debug('开始检测唤醒词...')
    try:
        while True:
            try:
                # 从音频流中读取数据
                pcm = stream.read(frame_length)
                if len(pcm) / frame_length == 2:
                    pcm = pcm[::2]
                result = porcupine.process(pcm)
                if result > 0:
                    print('检测到唤醒测!')
            except Exception as e:
                print(f'[warn] {str(e)}')
    except KeyboardInterrupt:
        print('停止运行.')
    # 清理资源
    stream.stop_stream()
    stream.close()
    audio.terminate()

def choose_device():
    # 初始化 PyAudio
    audio = pyaudio.PyAudio()
    # 列出所有音频输入设备
    for i in range(audio.get_device_count()):
        device_info = audio.get_device_info_by_index(i)
        if device_info['maxInputChannels'] > 0:
            print(f"Device {i}: {device_info['name']}")
    audio.terminate()
    print(40 * '*')
    print('>>请输入麦克风编号:', end='', flush=True)
    DEVICE_INDEX = sys.stdin.readline().strip()

if __name__ == '__main__':
    #choose_device()
    start_agent()
